package com.we.service.impl;

import com.we.dao.UserDao;
import com.we.entity.User;
import com.we.service.UserService;
import com.we.util.Base64Utils;
import com.we.util.MailUtils;
import com.we.util.MybatisUtils;
import com.we.util.UuidUtil;
import org.apache.ibatis.session.SqlSession;

/**
 * 用户业务逻辑接口实现类
 */
public class UserServiceImpl implements UserService {

    private SqlSession session = MybatisUtils.getSqlSession();
    private UserDao dao=session.getMapper(UserDao.class);

    /**
     * 根据用户名查询用户功能实现
     * @param userName
     * @return
     */
    @Override
    public User findUserByName(String userName) {
        return dao.findUserByName(userName);
    }

    /**
     * 根据邮箱查询用户功能实现
     * @param email
     * @return
     */
    @Override
    public User findUserByEmail(String email) {
        return dao.findUserByEmail(email);
    }

    /**
     * 用户注册功能实现
     * @param user
     * @return
     */
    @Override
    public boolean addUser(User user) {
        User u=dao.findUserByName(user.getUserName());
        User u1=dao.findUserByEmail(user.getEmail());
        if(u!=null || u1!=null){
            return false;
        }
        user.setCode(Base64Utils.encode(UuidUtil.getUuid()));
        user.setStatus("N");
        user.setIsAuthor("N");
        dao.addUser(user);
        String content = "<a href='http://localhost/wenote/user?method=active&code=" + user.getCode() + "'>点击激活【个人笔记系统】</a>";
        MailUtils.sendMail(user.getEmail(), content, "激活邮件");
        return true;
    }

    /**
     * 用户登录功能实现
     * @param user
     * @return
     */
    @Override
    public User login(User user) {
        return dao.findUserByNameAndPws(user.getUserName(),user.getPassword());
    }

    /**
     * 修改密码功能实现
     * @param password
     * @return
     */
    @Override
    public boolean updatePwd(String password,String userName) {
        int count = dao.updatePwd(password, userName);
        if(count<=0){
            return false;
        }else{
            return true;
        }
    }

    /**
     * 修改用户信息功能实现
     * @param user1
     * @return
     */
    @Override
    public int updateUserById(User user1) {
        return dao.updateUserById(user1);
    }

    /**
     * 找回密码功能实现
     * @param password
     * @param userName
     * @param email
     * @return
     */
    @Override
    public int forgetPws(String password, String userName, String email) {
        return dao.forgetPws(password,userName,email);
    }

    /**
     * 用户激活功能实现
     * @param code
     * @return
     */
    @Override
    public boolean active(String code) {
        User user=dao.findUserByCode(code);
        if(user!=null){
            dao.updateUserStatus(user);
            return true;
        }
        return false;
    }


}
